import Fluent
import FluentSQLiteDriver

@_exported import Vapor

// configures your application
public func configure(_ app: Application) throws {
    #if DEBUG
    app.setupServer()
    #endif
    
    app.setupContent()
    app.setupMiddleware()
    app.setupDatabase()
    
    try routes(app)
}

extension Application {
    func setupServer() {
        server.configuration.hostname = "0.0.0.0"
        server.configuration.port = 8080
    }
}

extension Application {
    func setupContent() {
        let encoder = JSONEncoder.snakeCase
        let decoder = JSONDecoder.snakeCase
//        encoder.dataEncodingStrategy = .millisecondsSince1970
//        decoder.dataDecodingStrategy = .millisecondsSince1970
        ContentConfiguration.global.use(decoder: decoder, for: .json)
        ContentConfiguration.global.use(encoder: encoder, for: .json)
    }
}

extension Application {
    func setupMiddleware() {
//        middleware.use(FileMiddleware(publicDirectory: directory.publicDirectory))
        middleware.use(YYFileMiddleware(publicDirectory: directory.publicDirectory))
        
        /// 跨域资源共享
        let corsConfiguration = CORSMiddleware.Configuration(
            allowedOrigin: .all,
            allowedMethods: [.GET, .POST, .PUT, .OPTIONS, .DELETE, .PATCH],
            allowedHeaders: [.accept, .authorization, .contentType, .origin, .xRequestedWith, .userAgent, .accessControlAllowOrigin]
        )
        middleware.use(CORSMiddleware(configuration: corsConfiguration))
    }
}

extension Application {
    func setupDatabase() {
        let path = directory.workingDirectory + "my.db"
        databases.use(.sqlite(file: path, maxConnectionsPerEventLoop: 1), as: .sqlite)
        
        migrations.add(CreateTodo())
    }
}
